package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author 胡慧
 * @title: ApUserRelationServiceImpl
 * @projectName heima-leadnews
 * @description: TODO
 * @date 2021/3/32:29
 */
@Service
@Transactional
@Slf4j
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    private ApUserFanMapper apUserFanMapper;
    @Autowired
    private ApUserFollowMapper apUserFollowMapper;
    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private IArticleClient iArticleClient;

    @Override
    public ResponseResult follow(UserRelationDto dto) {

        //1.参数检查
        if (dto.getOperation() == null || dto.getOperation() < 0 || dto.getOperation() > 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "作者信息不能为空");
        }
        //是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.获取作者
        ApAuthor apAuthor = iArticleClient.selectById(dto.getAuthorId());
        if (apAuthor == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "关注人不存在");
        }

        if (dto.getOperation() == 0) {
            //3.关注操作 保存用户关注和用户粉丝
            return followByUserId(user, apAuthor.getUserId(), dto.getArticleId());
        } else {
            //4.取消关注 删除用户关注和用户粉丝
            return followCancelByUserId(user, apAuthor.getUserId());
        }

    }

    /**
     * 取消关注
     *
     * @param apUser
     * @param followId
     * @return
     */
    private ResponseResult followCancelByUserId(ApUser apUser, Integer followId) {
        //查询关注对象
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getFollowId, followId)
                .eq(ApUserFollow::getUserId, apUser.getId()));
        if (apUserFollow == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "未关注");
        }
        //删除数据
        //查询粉丝信息
        ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getFansId, apUser.getId()).eq(ApUserFan::getUserId, followId));
        if (apUserFan != null) {
            apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getFansId, apUser.getId()).eq(ApUserFan::getUserId, followId));
        }
        //删除关注信息
        apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getFollowId, followId).eq(ApUserFollow::getUserId, apUser.getId()));

        //返回
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 关注作者
     *
     * @param loginUser 当前登录人
     * @param followId  作者对应的用户id
     * @param articleId 文章id,第十章会用
     * @return
     */
    private ResponseResult followByUserId(ApUser loginUser, Integer followId, Long articleId) {
        //得到用户信息
        ApUser followUser = apUserMapper.selectById(followId);
        if (followUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "关注人不存在");
        }
        //2.保存关注数据
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId, followUser.getId())
                .eq(ApUserFollow::getUserId, loginUser.getId()));
        if (apUserFollow == null) {
            //保存粉丝信息表
            ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getFansId, loginUser.getId())
                    .eq(ApUserFan::getUserId, followUser.getId()));
            if (apUserFan == null) {
                apUserFan = new ApUserFan();
                apUserFan.setUserId(followId);
                apUserFan.setFansId(loginUser.getId().longValue());
                apUserFan.setCreatedTime(new Date());
                apUserFan.setLevel((short) 0);
                apUserFan.setIsShieldComment(false);
                apUserFan.setIsShieldLetter(false);
                apUserFan.setIsDisplay(true);
                apUserFanMapper.insert(apUserFan);
            }
            //保存关注人
            apUserFollow = new ApUserFollow();
            apUserFollow.setFollowId(followId);
            apUserFollow.setUserId(loginUser.getId());
            apUserFollow.setLevel((short) 1);
            apUserFollow.setIsNotice(true);
            apUserFollow.setFollowName(followUser.getName());
            apUserFollow.setCreatedTime(new Date());
            apUserFollowMapper.insert(apUserFollow);
            //TODO 记录用户的行为
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {

            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "已关注");
        }
    }
}
